<?php

namespace app\api\controller;

use think\Controller;
use think\Log;

class Wechat extends Controller
{
    
    private $url = "https://api.weixin.qq.com/sns/oauth2/access_token?";
    
    private function setUrl($code){
        $appid = 'wx955e3fc4b9c1320b';
        $secret = 'd606f7540151def09a300158842c64cb';
        $this->url.="appid=$appid&secret=$secret&grant_type=authorization_code".'&code='.$code;
    }
    
    /**
     * @return mixed
     * @throws \Exception
     */
    public function getOpenId(){
        $code = input('code');
    
        if(empty($code)){
            Log::error('code error');
            puterror('code error');
        }
        
        $this->setUrl($code);
        $curl_res = curl_get($this->url);
        
        if(!$curl_res){
            log::error('curl_get error');
            puterror('curl_get error');
        }
        
        $array = json_decode($curl_res,true);
        if(empty($array['openid'])){
            Log::error($array);
            puterror($array['errmsg']);
        }
        
        return putsuccess($array['openid']);
    }
}

